package sys_serv

import (
	"encoding/json"
	"strconv"
	"strings"
	"ubt-rbac-service/internal/app/model"
	"ubt-rbac-service/internal/app/model/sys_mod"
	"ubt-rbac-service/internal/app/util"
	"ubt-rbac-service/internal/core/logger"
)

type sysUser struct{}

var SysUserServ = sysUser{}

// Login 用户登录
func (s *sysUser) Login(req *sys_mod.SysUserLoginReq) (*model.Result, string, string) {
	sqlStr := "SELECT a.user_id, a.usname, a.nick_name, a.mobile, a.states, b.role_name, b.mod_codes, b.btn_codes, a.dept_id " +
		"FROM sys_user a LEFT JOIN sys_role b ON a.role_id=b.role_id WHERE a.usname=$1 AND a.passwd=$2 "
	if dbMap, err := util.GetOne(sqlStr, req.Usname, req.Passwd); err == nil && len(dbMap) > 0 {
		if userJson, e1 := json.Marshal(dbMap); err == nil {
			// 将数据存储到Redis缓冲数据库中，键为随机的编号，值为获取到的用户信息数据
			userStr := string(userJson)
			token := util.NewNanoid()
			util.SaveUserInfo(token, userStr)
			return &model.Result{RetCode: 1001, RetMsg: "ok", RetData: token}, dbMap["userId"].(string), dbMap["deptId"].(string)
		} else if dbMap["states"] != 1 {
			return &model.Result{RetCode: 1002, RetMsg: "对不起，登录的账号被冻结，请联系系统管理员！"}, "", ""
		} else {
			logger.Error("用户登录信息数据转Json失败。" + e1.Error())
		}
	}
	return &model.Result{RetCode: 1002, RetMsg: "对不起，用户名或密码不正确，请重试！"}, "", ""
}

// Exit 用户登出
func (s *sysUser) Exit(req *sys_mod.SysUserExitReq) *model.Result {
	util.CleanUserInfo(req)
	return &model.Result{RetCode: 1001, RetMsg: "ok"}
}

// Add 新增用户
func (s *sysUser) Add(req *sys_mod.SysUserSaveReq) *model.Result {
	sqlStr := "INSERT INTO sys_user(usname, passwd, nick_name, mobile, role_id, dept_id, kind, states, add_time) " +
		"VALUES ($1, $2, $3, $4, $5, $6, $7, 1, EXTRACT(EPOCH FROM NOW()))"
	retCode, retMsg := util.CudData(sqlStr, req.Usname, req.Passwd, req.NickName, req.Mobile, req.RoleId, req.DeptId, req.Kind)
	return &model.Result{RetCode: retCode, RetMsg: retMsg}
}

// Exists 判断平台编码是否存在
func (s *sysUser) Exists(req *sys_mod.SysUserExtVo) bool {
	sqlStr := "SELECT COUNT(1) AS nums FROM sys_user WHERE states IN (1, 3) AND (usname=$1 OR mobile=$2)"
	param := make([]interface{}, 0)
	param = append(param, req.Usname)
	param = append(param, req.Mobile)
	if req.UserId != "" {
		sqlStr += " AND user_id!=$3"
		param = append(param, req.UserId)
	}
	if dbMap, err := util.GetOne(sqlStr, param...); err == nil {
		if dbMap["nums"].(int64) > 0 {
			return true
		}
	}
	return false
}

// Update 修改用户
func (s *sysUser) Update(req *sys_mod.SysUserSaveReq) *model.Result {
	var (
		sqlStr  string
		retCode uint32
		retMsg  string
	)
	if req.Passwd != "" {
		sqlStr = "UPDATE sys_user SET usname=$1, passwd=$2, nick_name=$3, mobile=$4, role_id=$5, dept_id=$6, kind=$7, upd_time=EXTRACT(EPOCH FROM NOW()) WHERE user_id=$8"
		retCode, retMsg = util.CudData(sqlStr, req.Usname, req.Passwd, req.NickName, req.Mobile, req.RoleId, req.DeptId, req.Kind, req.UserId)
	} else {
		sqlStr = "UPDATE sys_user SET usname=$1, nick_name=$2, mobile=$3, role_id=$4, dept_id=$5, kind=$6, upd_time=EXTRACT(EPOCH FROM NOW()) WHERE user_id=$7"
		retCode, retMsg = util.CudData(sqlStr, req.Usname, req.NickName, req.Mobile, req.RoleId, req.DeptId, req.Kind, req.UserId)
	}
	return &model.Result{RetCode: retCode, RetMsg: retMsg}
}

// Process 处理用户
func (s *sysUser) Process(req *sys_mod.SysUserProReq) *model.Result {
	var (
		param []interface{}
		q     string
		n     = 1
	)
	param = append(param, req.States)
	idList := strings.Split(req.UserIds, ",")
	for _, curId := range idList {
		n++
		q += "$" + strconv.Itoa(n) + ","
		param = append(param, curId)
	}
	q = q[:len(q)-1]
	sqlStr := "UPDATE sys_user SET states=$1, upd_time=EXTRACT(EPOCH FROM NOW()) WHERE user_id IN (" + q + ")"
	retCode, retMsg := util.CudData(sqlStr, param...)
	return &model.Result{RetCode: retCode, RetMsg: retMsg}
}

// GetPasswd 获取用户密码
func (s *sysUser) GetPasswd(userId string) string {
	sqlStr := "SELECT passwd FROM sys_user WHERE user_id=$1"
	if dbMap, err := util.GetOne(sqlStr, userId); err == nil && len(dbMap) > 0 {
		return dbMap["passwd"].(string)
	} else {
		return ""
	}
}

// Personal 修改个人资料
func (s *sysUser) Personal(req *sys_mod.SysUserInfoReq) *model.Result {
	var (
		sqlStr  string
		retCode uint32
		retMsg  string
	)
	if req.NewPasswd != "" {
		sqlStr = "UPDATE sys_user SET usname=$1, passwd=$2, nick_name=$3, mobile=$4, upd_time=EXTRACT(EPOCH FROM NOW()) WHERE user_id=$5"
		retCode, retMsg = util.CudData(sqlStr, req.Usname, req.NewPasswd, req.NickName, req.Mobile, req.UserId)
	} else {
		sqlStr = "UPDATE sys_user SET usname=$1, nick_name=$2, mobile=$3, upd_time=EXTRACT(EPOCH FROM NOW()) WHERE user_id=$4"
		retCode, retMsg = util.CudData(sqlStr, req.Usname, req.NickName, req.Mobile, req.UserId)
	}
	return &model.Result{RetCode: retCode, RetMsg: retMsg}
}

// One 获取用户详情
func (s *sysUser) One(userId string) *model.Result {
	sqlStr := "SELECT a.user_id, a.usname, '' passwd, a.nick_name, a.mobile, a.role_id, b.role_name, b.role_code, a.kind, " +
		"a.states, a.add_time, a.upd_time, a.dept_id, c.type_name, c.type_code " +
		"FROM sys_user a " +
		"LEFT JOIN sys_role b ON a.role_id=b.role_id " +
		"LEFT JOIN sys_type c ON a.dept_id=c.type_id " +
		"WHERE a.user_id=$1"
	if dbMap, err := util.GetOne(sqlStr, userId); err == nil && len(dbMap) > 0 {
		return &model.Result{RetCode: 1001, RetMsg: "ok", RetData: dbMap}
	} else {
		return &model.Result{RetCode: 1000, RetMsg: "暂无内容"}
	}
}

// Count 获取用户数量
func (s *sysUser) Count(req *sys_mod.SysUserPageReq) *model.Result {
	sqlStr := "SELECT COUNT(1) AS nums FROM sys_user WHERE states IN (1, 3)"
	param := make([]interface{}, 0)
	var n = 0
	if req != nil && req.SchName != "" {
		sqlStr += " AND ("
		nameArr := strings.Split(req.SchName, " ")
		for _, name := range nameArr {
			sqlStr += "usname LIKE '%'||$" + strconv.Itoa(n+1) + "||'%' OR " +
				"nick_name LIKE '%'||$" + strconv.Itoa(n+2) + "||'%' OR " +
				"mobile LIKE '%'||$" + strconv.Itoa(n+3) + "||'%' OR "
			param = append(param, name)
			param = append(param, name)
			param = append(param, name)
			n += 3
		}
		sqlStr = sqlStr[:len(sqlStr)-4]
		sqlStr += ")"
	}
	if req != nil && req.DeptId != "" {
		n++
		sqlStr += " AND dept_id=$" + strconv.Itoa(n)
		param = append(param, req.DeptId)
	}
	if req != nil && req.RoleId != "" {
		n++
		sqlStr += " AND role_id=$" + strconv.Itoa(n)
		param = append(param, req.RoleId)
	}
	if req != nil && req.States > 0 {
		n++
		sqlStr += " AND states=$" + strconv.Itoa(n)
		param = append(param, req.States)
	}
	if dbMap, err := util.GetOne(sqlStr, param...); err == nil {
		return &model.Result{RetCode: 1001, RetMsg: "ok", RetData: dbMap["nums"]}
	} else {
		return &model.Result{RetCode: 1000, RetMsg: "暂无内容"}
	}
}

// Page 获取用户分页列表
func (s *sysUser) Page(req *sys_mod.SysUserPageReq) *model.Result {
	sqlStr := "SELECT a.user_id, a.usname, a.nick_name, a.mobile, b.role_name, a.kind, c.type_name dept_name, a.states " +
		"FROM sys_user a " +
		"LEFT JOIN sys_role b ON a.role_id=b.role_id " +
		"LEFT JOIN sys_type c ON a.dept_id=c.type_id " +
		"WHERE a.states IN (1, 3)"
	param := make([]interface{}, 0)
	var n = 0
	if req != nil && req.SchName != "" {
		sqlStr += " AND ("
		nameArr := strings.Split(req.SchName, " ")
		for _, name := range nameArr {
			sqlStr += "a.usname LIKE '%'||$" + strconv.Itoa(n+1) + "||'%' OR " +
				"a.nick_name LIKE '%'||$" + strconv.Itoa(n+2) + "||'%' OR " +
				"a.mobile LIKE '%'||$" + strconv.Itoa(n+3) + "||'%' OR "
			param = append(param, name)
			param = append(param, name)
			param = append(param, name)
			n += 3
		}
		sqlStr = sqlStr[:len(sqlStr)-4]
		sqlStr += ")"
	}
	if req != nil && req.DeptId != "" {
		n++
		sqlStr += " AND a.dept_id=$" + strconv.Itoa(n)
		param = append(param, req.DeptId)
	}
	if req != nil && req.RoleId != "" {
		n++
		sqlStr += " AND a.role_id=$" + strconv.Itoa(n)
		param = append(param, req.RoleId)
	}
	if req != nil && req.States > 0 {
		n++
		sqlStr += " AND a.states=$" + strconv.Itoa(n)
		param = append(param, req.States)
	}
	sqlStr += " ORDER BY a.add_time DESC LIMIT $" + strconv.Itoa(n+1) + " OFFSET $" + strconv.Itoa(n+2)
	param = append(param, req.Limit)
	param = append(param, req.Offset)
	if dbMap, err := util.GetAll(sqlStr, param...); err == nil {
		return &model.Result{RetCode: 1001, RetMsg: "ok", RetData: dbMap}
	} else {
		return &model.Result{RetCode: 1000, RetMsg: "暂无内容"}
	}
}

// Select 获取用户下拉列表
func (s *sysUser) Select(req *sys_mod.SysUserSelReq) *model.Result {
	sqlStr := "SELECT user_id sel_id, nick_name sel_name, usname sel_code, false chked FROM sys_user WHERE states=1"
	param := make([]interface{}, 0)
	var n = 0
	if req.DeptId != "" {
		n++
		sqlStr += " AND dept_id=$" + strconv.Itoa(n)
		param = append(param, req.DeptId)
	}
	if req.SchName != "" {
		sqlStr += " AND ("
		nameArr := strings.Split(req.SchName, " ")
		for _, name := range nameArr {
			sqlStr += "usname LIKE '%'||$" + strconv.Itoa(n+1) + "||'%' OR " +
				"nick_name LIKE '%'||$" + strconv.Itoa(n+2) + "||'%' OR " +
				"mobile LIKE '%'||$" + strconv.Itoa(n+3) + "||'%' OR "
			param = append(param, name)
			param = append(param, name)
			param = append(param, name)
			n += 3
		}
		sqlStr = sqlStr[:len(sqlStr)-4]
		sqlStr += ")"
	}
	sqlStr += " ORDER BY nick_name"
	if dbMap, err := util.GetAll(sqlStr, param...); err == nil {
		return &model.Result{RetCode: 1001, RetMsg: "ok", RetData: dbMap}
	} else {
		return &model.Result{RetCode: 1000, RetMsg: "暂无内容"}
	}
}
